package fr.liglab.adele.icasa.house.test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.felix.ipojo.annotations.Bind;
import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Instantiate;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.Unbind;
import org.apache.felix.ipojo.annotations.Validate;

import fr.liglab.adele.icasa.device.presence.AudioSource;
import fr.liglab.adele.icasa.device.presence.Speaker;
import fr.liglab.adele.icasa.house.abstraction.Room;
import fr.liglab.adele.icasa.house.device.impl.SimulatedSpeakerImpl;
import fr.liglab.adele.icasa.house.device.impl.SumulatedAudioSourceImpl;
import fr.liglab.adele.icasa.house.factory.dao.GenesisDeviceDAO;
import fr.liglab.adele.icasa.house.util.PrettyPrint;
import fr.liglab.adele.icasa.house.util.RoomAdvertiseListener;

@Component
@Instantiate
public class Monitor extends Thread implements RoomAdvertiseListener{

	//@Requires(specification = "fr.liglab.adele.icasa.house.util.Room")
	private List<Room> rooms=new ArrayList<Room>();

	@Requires
	private AudioSource ias;//=new SumulatedAudioSourceImpl();
	
	private boolean state=true;

	@Bind(aggregate=true)
	private synchronized void bindSrv(Room room){
		System.out.println("Binding");
		rooms.add(room);
	}
	
	@Unbind(aggregate=true)
	private synchronized void unbindSrv(Room room){
		rooms.remove(room);
	}
	
	@Validate
	public void validate() {
		this.start();
		ias.play();
	}

	@Invalidate
	public void invalidate() {
		System.out.println("Stopping..");
		state = false;
	}
	
	public void run() {
		while (state) {
			System.out.println("\n\n<rooms>");
			for (Room r : rooms) {							
				List devi=r.getDevices();
				Iterator it=devi.iterator();
				r.addListener(this);				
				while(it.hasNext()){					
					GenesisDeviceDAO g=(GenesisDeviceDAO)it.next();						
					PrettyPrint.printcomponent(g);				
				}
			}			
			System.out.println("</rooms>");		
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public void onSoundRoomActivate(Room room,Speaker speaker) {
		speaker.setSource(ias);
	}
	
	public void onSoundRoomDeactivate(Room room,Speaker speaker) {
		speaker.unsetSource();
	}
	
	public static void main(String[] args) {
		AudioSource ias=new SumulatedAudioSourceImpl();
		Speaker spek=new SimulatedSpeakerImpl();
		spek.setSource(ias);
		ias.play();
		spek.turnon();
		
		try {
			Thread.sleep(20000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
